import json

from common.bankcard import db as cards
from common.mch import db as merchant
from common.range import db as range
from common.utils.decorator import response_wrapper
from django.views.decorators.http import require_GET, require_POST


@require_GET
@response_wrapper
def get_range_list(request):
    data = request.GET.dict()
    card = data.get('card_code')

    items = range.list_range(data)
    result_list, result = range.get_range_dict(items, data, card)

    return {"list": result_list, 'page': data.get('$page', 1),
            'size': len(result_list), 'total_count': len(result)}

@require_POST
@response_wrapper
def add_range(request):
    data = json.loads(request.body)
    result = range.insert_range(data)
    result = result.as_dict()
    return {'id': result['id']}


@require_POST
@response_wrapper
def edit_range(request):
    data = json.loads(request.body)
    result = range.update_range(data, data['id'])
    result = result.as_dict()
    return {"data": result['id']}


@require_POST
@response_wrapper
def edit_status_range(request):
    data = json.loads(request.body)
    result = range.update_range_status(data, data['id'])
    result = result.as_dict()
    return {"data": result['id']}


@require_POST
@response_wrapper
def assign_cards_companies(request):
    data = json.loads(request.body)
    result = range.assign_cards_to_range(data)
    # result.as_dict()
    return result


"""GET CARDS ONLY"""


@require_GET
@response_wrapper
def get_cards(request):
    data = cards.get_cards_only()
    return data


"""GET RANGE ONLY"""


@require_GET
@response_wrapper
def get_range(request):
    data = range.get_range_only()
    return data


"""GET COMPANNIES ONLY"""


@require_GET
@response_wrapper
def get_company(request):
    data = merchant.get_company_only()
    return data


@require_GET
@response_wrapper
def get_order_deposit_list(request):
    data = request.GET.dict()
    cards = range.list_order_deposit(data['card'])
    return  {"list": cards, "size": len(cards)}

@require_GET
@response_wrapper
def get_order_withdraw_list(request):
    data = request.GET.dict()
    cards = range.list_order_withdraw(data['card'])
    return {"list": cards, "size": len(cards)}
